import 'dart:io';
import 'dart:typed_data';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:path_provider/path_provider.dart';
import 'package:video_compress/video_compress.dart';

/// 压缩返回类型
class CompressMediaFile {
  /// 缩略图
  final File? thumbnail;

  /// 媒体文件
  final MediaInfo? video;

  CompressMediaFile({
    this.thumbnail,
    this.video,
  });
}

/// 压缩类
class DuCompress {
  ///压缩图片
  static Future<XFile?> image(
    File file, {
    int minWidth = 1920,
    int minHeight = 1080,
  }) async {
    return await FlutterImageCompress.compressAndGetFile(
      file.path,
      '${file.path}_temp.jpg',
      keepExif: true,
      quality: 80,
      format: CompressFormat.jpeg,
      minHeight: minHeight,
      minWidth: minWidth,
    );
  }

  /// 压缩视频
  static Future<CompressMediaFile> video(File file) async {
    try {
      var result = await Future.wait([
        VideoCompress.compressVideo(
          file.path,
          quality: VideoQuality.Res640x480Quality,
          deleteOrigin: false,
          includeAudio: true,
          frameRate: 25,
        ),
        VideoCompress.getByteThumbnail(
          file.path,
          quality: 80,
          position: -1,
        ),
      ]);

      // 获取缩略图的 Uint8List
      Uint8List thumbnailData = result[1] as Uint8List;

      // 将 Uint8List 转换为 File 对象
      final tempDir = await getTemporaryDirectory();
      final thumbnailFile = File('${tempDir.path}/thumbnail.jpg');
      await thumbnailFile.writeAsBytes(thumbnailData);

      return CompressMediaFile(
        video: result[0] as MediaInfo,
        thumbnail: thumbnailFile,
      );
    } catch (e) {
      print('Video compression failed: $e');
      return CompressMediaFile(video: null, thumbnail: null);
    }
  }

  /// 清理缓存
  static Future<bool?> clean() async {
    return await VideoCompress.deleteAllCache();
  }

  /// 取消
  static Future<void> cancel() async {
    await VideoCompress.cancelCompression();
  }
}
